import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_base/src/common/widgets/loading_dialog_widget.dart';
import 'package:flutter_base/src/config/app_colors.dart';
import 'package:flutter_base/src/utils/navigation_service.dart';

/// 全屏Loading弹窗
class LoadingUtils {
  static bool _isShowLoading = false; // 是否显示loading
  static bool _alreadyShow = false; // loading是否已经展示在界面上
  static Timer? _loadingTimer; // 保存定时器实例

  /// 显示加载框
  static void showLoading({required BuildContext context, String message = ''}) {
    showLoadingDialog(context: context, message: message);
  }

  /// 显示加载框
  static void showLoadingDialog({required BuildContext context, String message = ''}) {
    if (_isShowLoading) return;
    if (!context.mounted) return;
    _isShowLoading = true;
    if (_isLayoutCompleted(context)) {
      if (message.isEmpty) {
        message = '加载中...';
      }
      _showDialog(context, message);
    } else {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (!context.mounted) {
          _isShowLoading = false;
          return;
        }
        if (message.isEmpty) {
          message = '加载中...';
        }
        _showDialog(context, message);
      });
    }
  }

  static void _showDialog(BuildContext context, String message) {
    showDialog(
      context: context,
      barrierDismissible: false, // 禁止点击外部关闭
      builder: (BuildContext context) {
        return PopScope(
          canPop: false, // 禁止返回键关闭
          child: Dialog(
            backgroundColor: AppColors.of(context).whiteColor,
            insetPadding: const EdgeInsets.all(0),
            child: LoadingDialogWidget(message: message),
          ),
        );
      },
    ).then((_) {
      _isShowLoading = false;
      _alreadyShow = false;
    });
    _loadingTimer = Timer(const Duration(seconds: 35), () {
      dismissLoading();
    });
  }

  /// 关闭加载框
  static void dismissLoading() {
    _isShowLoading = false;
    if (_alreadyShow) {
      _alreadyShow = false;
      _loadingTimer?.cancel();
      _loadingTimer = null;
      Navigator.of(NavigationService.context, rootNavigator: true).pop();
    }
  }

  /// loading弹窗已显示在界面上
  static void dialogAlreadyShow() {
    _alreadyShow = true;
    if (!_isShowLoading) {
      dismissLoading();
    }
  }

  static bool _isLayoutCompleted(BuildContext context) {
    final renderObject = context.findRenderObject();
    return renderObject != null && renderObject.attached;
  }
}
